package com.sm.filter;

import com.sm.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class JwtGlobalFilter implements GlobalFilter, Ordered {

	@Autowired
	private JwtUtils jwtUtils;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 获取request
		ServerHttpRequest request = exchange.getRequest();

		// 是否为需要过滤的请求
		if(isExclude(request.getPath().toString())) {
			return chain.filter(exchange);
		}

		// 获取token
		String token = null;
		List<String> authorizations = request.getHeaders().get("authorization");
		if(authorizations != null) {
			token = authorizations.get(0);
		}

		Claims claims = jwtUtils.parserToken(token);
		Long userId = Long.valueOf(claims.get("userId").toString());

		ServerWebExchange userIdExchange = exchange.mutate().request(r -> r.header("userId", userId.toString())).build();

		return chain.filter(userIdExchange);
	}

	private boolean isExclude(String path) {
		return path.startsWith("/user/login") || path.startsWith("/user/register");
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
